﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class SheetView : DataGridViewPopup
    {
        public void SortTemplate()
        {
            if (Mode != SheetType.Template)
            {
                return;
            }
            
            Sort(new RowComparer());

            Columns[0].HeaderCell.SortGlyphDirection = SortOrder.None;
        }
        
        internal WorkingHoursSpan averageTime(DataGridViewRow pRow)
        {
            if (pRow == null)
            {
                return default(WorkingHoursSpan);
            }
            var underlying = UnderlyingRow(pRow.Index);
            var openTime = 0;
            var closeTime = 0;
            var index = 0;
            
            foreach (var shift in underlying.SelectMany(cell => cell.Shifts.ToArray()))
            {
                openTime += shift.Start.Time;
                closeTime += shift.Finish.Time;
                index++;
            }

            var result = default(WorkingHoursSpan);
            if (index > 0)
            {
                result.Open = new TimeByQuarters(Convert.ToByte(openTime / index));
                result.Close = new TimeByQuarters(Convert.ToByte(openTime / index));
            }
            return result;
        }

        private class RowComparer : IComparer
        {
            

            public int Compare(object x, object y)
            {
                var rowX = x as DataGridViewRow;
                var rowY = y as DataGridViewRow;
                if (rowX == null || 
                    rowY == null ||
                    rowX.Cells.Count == 0 ||
                    rowY.Cells.Count == 0 ||
                    rowX.Cells[0].Value.GetType() != typeof(Position) ||
                    rowY.Cells[0].Value.GetType() != typeof(Position))
                {
                    return 0;
                }
                var positionX = (Position)rowX.Cells[0].Value;
                var positionY = (Position)rowY.Cells[0].Value;
                if (positionX == positionY &&
                    rowX.DataGridView is SheetView &&
                    rowY.DataGridView is SheetView)
                {
                    return (rowX.DataGridView as SheetView).averageTime(rowX).CompareTo(
                        (rowY.DataGridView as SheetView).averageTime(rowY));
                }
                return ((Position) rowX.Cells[0].Value).CompareWith(
                    (Position) rowY.Cells[0].Value);
            }
        }
    }
}
